package com.yanqu.road.server.manger.union;

import com.yanqu.road.entity.activity.unionwar.cross.UnionWarUserData;
import com.yanqu.road.logic.bussiness.union.UnionWarBussiness;
import com.yanqu.road.logic.union.UnionWarManger;
import com.yanqu.road.logic.pb.UnionWarPb;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.union.*;
import com.yanqu.road.pb.unionwar.UnionWarProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UnionWarMgr extends TempMgr {

    private static Object lockObj = new Object();

    private static Map<Integer, Map<String, UnionWarDetail>> unionWarDetailMap;

    @Override
    public boolean reloadData() {
        UnionWarManger.parseUnionWarDate();
        int mark = UnionWarManger.getNowMark();
        unionWarDetailMap = UnionWarBussiness.getUnionWarDetailMap(mark);
        for(UnionWarDetail unionWarDetail : unionWarDetailMap.get(mark).values()){
            UnionWarManger.orderUserPatronsList(unionWarDetail);
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        int mark = UnionWarManger.getNowMark();
        if (unionWarDetailMap.containsKey(mark)) {
            for (String unionUid : unionWarDetailMap.get(mark).keySet()) {
                UnionWarDetail unionWarDetail = unionWarDetailMap.get(mark).get(unionUid);
                if (unionWarDetail.isInsertOption()) {
                    UnionWarBussiness.addUnionWarDetail(unionWarDetail);
                } else if (unionWarDetail.isUpdateOption()) {
                    UnionWarBussiness.updateUnionWarDetail(unionWarDetail);
                }
            }
        }
        return true;
    }

    public static int dispatchPatrons(GamePlayer player, int patronsId) {
        UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
        if (null == userPatrons) {
            return GameErrorCode.E_PATRONS_NO_FOUND;
        }
        return 0;
    }

    public static int recallPatrons(GamePlayer player, int patronsId) {
        UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
        if (null == userPatrons) {
            return GameErrorCode.E_PATRONS_NO_FOUND;
        }

        if (!UnionWarManger.isPrepareTime()) {
            return GameErrorCode.E_UNION_WAR_NO_PREPARE_TIME;
        }

//        return backTalent(player, unionId, patronsId, getNowTimeMark());
        return 0;
    }

    public static int replacePatrons(GamePlayer player, int oldPatronsId, int newPatronsId) {
        PatronsModule patronsModule = player.getModule(PatronsModule.class);
        UserPatrons newPatrons = patronsModule.getUserPatrons(newPatronsId);
        UserPatrons oldPatrons = patronsModule.getUserPatrons(oldPatronsId);
        if (newPatrons == null || oldPatrons == null) {
            return GameErrorCode.E_PATRONS_NO_FOUND;
        }

        if (!UnionWarManger.isPrepareTime()) {
            return GameErrorCode.E_UNION_WAR_NO_PREPARE_TIME;
        }

        return 0;
    }

    public static int useBook(GamePlayer player, int bookId) {
        UnionWarUserData unionWarUserData = null;
        int mark = UnionWarManger.getNowMark();
        String unionUid = player.getUserInfo().getUnionUid();
        UnionWarDetail unionWarDetail;
        synchronized (lockObj) {
//            if (!unionWarDetailMap.containsKey(mark) || !unionWarDetailMap.get(mark).containsKey(unionUid) ||
//                    !unionWarDetailMap.get(mark).get(unionUid).getUserDataMap().containsKey(player.getUserId()) ||
//                    unionWarDetailMap.get(mark).get(unionUid).getUserDataMap().get(player.getUserId()).getPatronsMap().size() != 1 ) {
//                return GameErrorCode.E_UNION_WAR_NO_DISPATCH_PATRONS;
//            }

            initMarkUnionWarInfo(mark, unionUid, player.getUserId());
            unionWarDetail = unionWarDetailMap.get(mark).get(unionUid);
            unionWarUserData = unionWarDetail.getUserUnionWarInfoMap().get(player.getUserId());

//            if (unionWarUserData.getPatronsMap().size() == 0) {
//                return GameErrorCode.E_UNION_WAR_NO_DISPATCH_PATRONS;
//            }

//            if (unionWarUserData.getBookId() != 0) {
//                return GameErrorCode.E_UNION_WAR_HAS_USE_BOOK;
//            }

            // 扣除道具
            if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(bookId, BigInteger.ONE), eLogMoneyType.Union, eLogMoneyType.UnionWarUseBook)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
//            unionWarUserData.setBookId(bookId);
            unionWarDetail.setLastUpdateTime(System.currentTimeMillis());
            unionWarDetail.setUpdateOption();
            UnionWarManger.orderUserPatronsList(unionWarDetail);
        }

        syncUnionWarDetail(player, unionWarDetail);
        return 0;
    }

    public static int donateSilver(GamePlayer player, BigInteger silver) {
        int mark = UnionWarManger.getNowMark();
        String unionUid = player.getUserInfo().getUnionUid();
        if (!unionWarDetailMap.containsKey(mark) || null == unionWarDetailMap.get(mark).get(unionUid) ||
                UnionWarManger.getUnionWarJoinUserCount(unionWarDetailMap.get(mark).get(unionUid)) < GameConfig.UNION_WAR_MIN_JOIN_COUNT) {
            return GameErrorCode.E_UNION_WAR_NO_JOIN;
        }

        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_SILVER, silver),
                eLogMoneyType.Union, eLogMoneyType.UnionWarDonate)) {
            return GameErrorCode.E_BAG_SILVER_NO_ENOUGH;
        }

        UnionWarDetail unionWarDetail = unionWarDetailMap.get(mark).get(unionUid);
        synchronized (unionWarDetail) {
            unionWarDetail.setTotalDonateSilver(unionWarDetail.getTotalDonateSilver().add(silver));
        }

        if (unionWarDetail.getUserDonateMap().containsKey(player.getUserId())) {
            BigInteger newSilver = unionWarDetail.getUserDonateMap().get(player.getUserId()).getValue().add(silver);
            unionWarDetail.getUserDonateMap().get(player.getUserId()).setValue(newSilver);
        } else {
            UnionWarUserRank unionWarUserRank = new UnionWarUserRank();
            UnionMember member = UnionMgr.getUnionMember(unionUid, player.getUserId());
            if (null != member) {
                unionWarUserRank.setPosition(member.getPosition());
            }

            UserInfo userInfo = player.getUserInfo();
            unionWarUserRank.setUserId(player.getUserId());
            unionWarUserRank.setNickName(userInfo.getNickName());
            unionWarUserRank.setTitleId(userInfo.getTitleId());
            unionWarUserRank.setDecoration(UserMgr.getDecoration(userInfo.getUserId()));
            unionWarUserRank.setCity(userInfo.getCity());
            unionWarUserRank.setValue(silver);
            unionWarDetail.getUserDonateMap().put(player.getUserId(), unionWarUserRank);
        }
        unionWarDetail.setUpdateOption();
        return 0;
    }

    private static void syncUnionWarDetail(GamePlayer player, UnionWarDetail unionWarDetail){
        UnionWarProto.UnionWarDetailMsg.Builder msg = UnionWarPb.parseUnionWarDetailMsg(unionWarDetail, false);
        player.sendPacket(Protocol.U_UNION_WAR_PATRONS_DATA, msg);
    }

    public static void initMarkUnionWarInfo(int mark, String unionUid, long userId) {
        if (!unionWarDetailMap.containsKey(mark)) {
            unionWarDetailMap.put(mark, new ConcurrentHashMap<>());
        }

        UnionWarDetail unionWarDetail = unionWarDetailMap.get(mark).get(unionUid);
        if (null == unionWarDetail) {
            unionWarDetail = new UnionWarDetail(unionUid);
            unionWarDetail.setInsertOption();
            unionWarDetail.setTotalDonateSilver(BigInteger.ZERO);
            UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
            if (null != unionInfo) {
                unionWarDetail.setUnionName(unionInfo.getUnionName());
                unionWarDetail.setUnionFlag(unionInfo.getUnionFlag());
                unionWarDetail.setMasterNickName(unionInfo.getMasterNickName());
                unionWarDetail.setUnionExp(unionInfo.getExperience());
            }
            unionWarDetailMap.get(mark).put(unionUid, unionWarDetail);
        }

        if (!unionWarDetail.getUserUnionWarInfoMap().containsKey(userId)) {
            UnionWarUserData unionWarUserData = new UnionWarUserData();
            unionWarUserData.setUserId(userId);
//            unionWarUserData.setBookId(0);
            unionWarDetail.getUserUnionWarInfoMap().put(userId, unionWarUserData);
            unionWarDetail.setUpdateOption();
        }
    }

    public static UnionWarDetail getUnionWarDetail(String unionUid){
        int mark = UnionWarManger.getNowMark();
        if(unionWarDetailMap.containsKey(mark)){
            return unionWarDetailMap.get(mark).get(unionUid);
        }
        return null;
    }
}
